//
//  JZBDetailViewController.m
//  JZB
//
//  Created by  on 2022/8/29.
//

#import "JZBDetailViewController.h"
#import "JZBHeader.h"
#import "JZBDetailCell.h"
#import "JZBDetailHeader.h"
#import "JZBPopDetailViewController.h"
#import "JZBAddPayViewController.h"

@interface JZBDetailViewController ()
@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, strong) JZBHeader *header;
@property (nonatomic, assign) AddStyle type;

@end

@implementation JZBDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(actionUpdate:) name:notifyUserUpdate object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(actionUpdate:) name:notifyBookUpdate object:nil];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [RLHud stopHud];
}
- (void)initUI
{
    self.backBtn.hidden = YES;
    self.header = [JZBHeader loadFromXIB];
    self.header.title.text = LS(@"账单明细");
    WS(self)
    self.header.block = ^(int tag) {
        if (tag == 202) {
            weakself.type = AddStylePay;
        }else if (tag == 203){
            weakself.type = AddStyleIncome;
        }
    };
    self.type = AddStylePay;
    self.header.btn.hidden = YES;
    self.header.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.header];
    NSLayoutConstraint *top = [self.header a1:NSLayoutAttributeTop e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeTop c:0];
    NSLayoutConstraint *left = [self.header a1:NSLayoutAttributeLeft e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeLeft c:0];
    NSLayoutConstraint *height = [self.header a1:NSLayoutAttributeHeight e:NSLayoutRelationEqual t:nil a2:NSLayoutAttributeNotAnAttribute c:120];
    NSLayoutConstraint *right = [self.header a1:NSLayoutAttributeRight e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeRight c:0];
    [self.view addConstraints:@[top,left,height,right]];
    
    self.tableviewstyle = UITableViewStyleGrouped;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.tableView registerNib:[JZBDetailCell nib] forCellReuseIdentifier:[JZBDetailCell ID]];
    for (NSLayoutConstraint *c in self.view.constraints) {
        if ([c.firstItem isEqual:self.tableView]) {
            c.active = NO;
        }
    }
    NSLayoutConstraint *top1 = [self.tableView a1:NSLayoutAttributeTop e:NSLayoutRelationEqual t:self.header a2:NSLayoutAttributeBottom c:0];
    NSLayoutConstraint *left1 = [self.tableView a1:NSLayoutAttributeLeft e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeLeft c:20];
    NSLayoutConstraint *bottom = [self.tableView a1:NSLayoutAttributeBottom e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeBottom c:-TabBarHight];
    NSLayoutConstraint *right1 = [self.tableView a1:NSLayoutAttributeRight e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeRight c:-20];
    [self.view addConstraints:@[top1,left1,bottom,right1]];
    
}
- (void)setType:(AddStyle)type{
    _type = type;
    [self actionUpdate:nil];
}
- (void)actionUpdate:(NSNotification *)notify{
    [RLHud startHud:LS(@"获取数据中...")];
    self.array = [NSMutableArray array];
    int stamp = [[NSDate currentTimeStamp:@"yyyy/MM/dd"] intValue];
    NSDateComponents *com = [NSDate dateOfStamp:stamp];
    ///获取最近十年的数据
    for (int i = (int)com.year; i >= com.year; i--) {
        for (int j = (int)com.month ; j >= 1; j--) {
            ///获取当前月份的天数
            NSString *str = [NSString stringWithFormat:@"%d/%d/1",i,j];
            int temp = [[NSDate tranToStamp:str :@"yyyy/MM/dd"] intValue];
            int day = j == com.month ? (int)com.day : (int)[NSDate numOfMonth:temp];
            for (int n = day; n >= 1; n--) {
                NSString* where = [NSString stringWithFormat:@"where %@=%@ and %@=%@ and %@=%@ and %@=%@ and %@=%@",bg_sqlKey(@"userID"),bg_sqlValue(APP.user.ID),bg_sqlKey(@"year"),bg_sqlValue(@(i)),bg_sqlKey(@"month"),bg_sqlValue(@(j)),bg_sqlKey(@"day"),bg_sqlValue(@(n)),bg_sqlKey(@"ispay"),bg_sqlValue(@(self.type == AddStylePay))];
                [JZBBook bg_findAsync:nil where:where complete:^(NSArray * _Nullable array) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (array.count > 0) {
                            JZBBook *model = array[0];
                            NSString *key = [NSString stringWithFormat:LS(@"%@-%@/%@/%d笔"),model.month,model.day,LS(model.week),(int)array.count];
                            [self.array addObject:@{key:array}];
                        }
                        [RLHud stopHud];
                        [self.tableView reloadData];
                    });
                }];
            }
            
        }
    }
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.array.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  [[[self.array[section] allValues] firstObject] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JZBDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:[JZBDetailCell ID]];
    NSArray *array = [[self.array[indexPath.section] allValues] firstObject];
    JZBBook *model = array[indexPath.row];
    cell.img.image = [UIImage imageNamed:model.type];
    cell.name.text = LS(model.type);
    cell.money.text = [NSString stringWithFormat:@"%@%@",self.type == AddStylePay ? @"-":@"+" ,model.money];
    cell.line.hidden = indexPath.row == [array count] - 1;
    if (model.data.count > 0) {
        cell.userImg.image = [UIImage imageWithData:model.data[0]];
    }
    return  cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 57;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 57)];
    view.backgroundColor = [UIColor clearColor];
    JZBDetailHeader *header = [JZBDetailHeader loadFromXIB];
    header.frame = view.bounds;
    NSString *key = [[self.array[section] allKeys] firstObject];
    NSArray *array = [[self.array[section] allValues] firstObject];
    int total = 0;
    for (JZBBook *book in array) {
        total += [book.money intValue];
    }
    header.title.text = key;
    if (self.type == AddStylePay) {
        header.money.text = [NSString stringWithFormat:@"-%d",total];
        header.money.textHexColor = @"#34C8A5";
    }else if (self.type == AddStyleIncome){
        header.money.text = [NSString stringWithFormat:@"+%d",total];
        header.money.textHexColor = @"#FF5050";
    }
    [view addSubview:header];
    return view;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray * array = [[self.array[indexPath.section] allValues] firstObject];
    JZBBook *model = array[indexPath.row];
    
    JZBPopDetailViewController *vc = [JZBPopDetailViewController new];
    vc.style = self.type;
    vc.model = model;
    WS(self)
    vc.block = ^(int tag) {
        if (tag == 202){
            [RLHud startHud:LS(@"删除中...")];
            NSString* where = [NSString stringWithFormat:@"where %@=%@ and %@=%@ and %@=%@",bg_sqlKey(@"userID"),bg_sqlValue(APP.user.ID),bg_sqlKey(@"stamp"),bg_sqlValue(@(model.stamp)),bg_sqlKey(@"ispay"),bg_sqlValue(@(self.type == AddStylePay))];
            [JZBBook bg_deleteAsync:nil where:where complete:^(BOOL isSuccess) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakself actionUpdate:nil];
                    [RLHud startHud:LS(@"删除成功") stopTime:1 handle:^{}];
                });
            }];
        }else if (tag == 203){
            JZBAddPayViewController *vc = [JZBAddPayViewController new];
            vc.style = weakself.type;
            vc.model = model;
            [weakself.navigationController pushViewController:vc animated:YES];
        }
    };
    [self presentViewController:vc animated:NO completion:nil];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray * array = [[self.array[indexPath.section] allValues] firstObject];
    if (indexPath.row == 0 || indexPath.row == array.count - 1) {
        UIBezierPath *path;
        if (indexPath.row == 0 && indexPath.row != array.count -1) {
            path = [UIBezierPath bezierPathWithRoundedRect:cell.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
        }else if(indexPath.row != 0 && indexPath.row == array.count -1){
            path = [UIBezierPath bezierPathWithRoundedRect:cell.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
        }else if (indexPath.row == 0 && indexPath.row == array.count - 1){
            path = [UIBezierPath bezierPathWithRoundedRect:cell.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
        }
        CAShapeLayer *layer = [CAShapeLayer layer];
        layer.frame = cell.bounds;
        layer.path = path.CGPath;
        cell.layer.mask = layer;
    }else{
        cell.layer.mask = nil;
    }
}

@end
